package com.apes.framework.plugin.condition.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.condition.model.ConditionField;
import com.apes.framework.plugin.condition.repository.ConditionFieldRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 条件字段
 *
 * @author wuq
 * @create 2018-11-12 16:40
 */
@Service
public class ConditionFieldService extends DomainService {

    @Autowired
    ConditionFieldRepository conditionFieldRepository;

    public ConditionField save(SimpleRequest request) {
        ConditionField conditionField = request.getO(ConditionField.class);

        // 数据检查
        if (conditionField.getWidgetType() != null) {
            // 控件判断
            if ("select".equalsIgnoreCase(conditionField.getWidgetType().getId())
                    && (conditionField.getApi() == null || "".equals(conditionField.getApi())))
                throw new RuntimeException("选择 select 控件时，需要填写 API 字段");
        }

        return conditionFieldRepository.saveAndFlush(conditionField);
    }

    public void checkData(SimpleRequest request) {
        String id = request.get("id");
        // 从数据库中取数，检查数据
        ConditionField oldConditionField = conditionFieldRepository.findOne(id);
        if (oldConditionField == null) throw new RuntimeException("条件字段【" + id + "】在系统中不存在。");
    }

    public ConditionField update(SimpleRequest request) {
        checkData(request);

        ConditionField conditionField = request.getO(ConditionField.class);
        // 数据检查
        if (conditionField.getWidgetType() != null) {
            // 控件判断
            if ("select".equalsIgnoreCase(conditionField.getWidgetType().getId())
                    && (conditionField.getApi() == null || "".equals(conditionField.getApi())))
                throw new RuntimeException("选择 select 控件时，需要填写 API 字段");
        }
        return conditionFieldRepository.saveAndFlush(conditionField);
    }

    public String delete(SimpleRequest request) {
        checkData(request);
        ConditionField conditionField = request.getO(ConditionField.class);
        conditionFieldRepository.delete(conditionField);
        return "删除成功";
    }

    /**
     * 功能：下拉模糊查询使用
     *
     * @param request
     * @return
     */
    public Page<ConditionField> find(SimpleRequest request) {
        String value = request.get("key");
        return conditionFieldRepository.find(value, value, PageRequest.of(request.get("page"), request.get("size")));
    }

    public List<ConditionField> findAll() {
        return conditionFieldRepository.findAll();
    }

}
